package com.shoesmail.service.impl;

import com.shoesmail.annotation.JwtToken;
import com.shoesmail.constants.RedisConstants;
import com.shoesmail.domain.dto.AddUserDto;
import com.shoesmail.domain.dto.QueryUserDto;
import com.shoesmail.domain.query.user.UserLoginQuery;
import com.shoesmail.domain.query.user.UserRegisterQuery;
import com.shoesmail.domain.vo.JsonResultVo;
import com.shoesmail.domain.vo.user.UserRegisterVo;
import com.shoesmail.enums.RoleEnum;
import com.shoesmail.mapper.AccountMapper;
import com.shoesmail.mapper.UserMapper;
import com.shoesmail.service.AccountGenericService;
import com.shoesmail.service.UserLoginService;
import com.shoesmail.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author ：CDB
 * @description：用户登陆注册相关
 * @date ：2025/9/17 9:52
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private EmailSendUtil emailSendUtil;

    @Value("${mail.text}")
    private String codeText;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AccountGenericService accountGenericService;

    @Autowired
    private UserMapper userMapper;

    @Value("${mail.account_text}")
    private String accountText;
    /**
     * 发送验证码
     * @param email ：邮箱
     * @return 成功与否
     */
    @Override
    public JsonResultVo<Boolean> sendEmailCode(String email) {
        String code = CodeUtil.getCode(4);
        boolean succ = emailSendUtil.sendMail(email, codeText.replace("{}", code));
        if(succ){
            stringRedisTemplate.opsForValue().set(RedisConstants.EMAIL_CODE+email,code,60, TimeUnit.SECONDS);
            return JsonResultVo.success("发送验证码成功",true);
        }
        return JsonResultVo.fail("发送验证码失败，请联系管理员");
    }


    /**
     * 用户注册
     * @param userRegisterQuery 注册参数
     * @return token等信息
     */
    @Override
    public JsonResultVo<UserRegisterVo> register(UserRegisterQuery userRegisterQuery) {
        if(userRegisterQuery==null){
            return JsonResultVo.fail("传入信息为空");
        }
        String password = userRegisterQuery.getPassword();
        String confirmPasd = userRegisterQuery.getConfirmPasd();
        if(!password.equals(confirmPasd)){
            return JsonResultVo.fail("两次密码不一致");
        }

        String email = userRegisterQuery.getEmail();

        String redisCode = stringRedisTemplate.opsForValue().get(RedisConstants.EMAIL_CODE + email);
        if(StringUtils.isNull(redisCode)||!redisCode.equals(userRegisterQuery.getCode())){
            return JsonResultVo.fail("验证码错误");
        }
        Long account = AccountUtil.getAccount(accountMapper, accountGenericService);
        if(account==null){
            return JsonResultVo.fail("系统错误，生成账号失败，请联系管理员");
        }

        boolean b = emailSendUtil.sendMail(email, accountText.replace("{}", account.toString()));
        if(!b){
            return JsonResultVo.fail("注册账号失败，请联系管理员");
        }

        //加密字段
        String salt = CodeUtil.getCode(4);

        //存储数据库的密码
        String pasd = CodeUtil.md5(password + salt);

        AddUserDto addUserDto = new AddUserDto(userRegisterQuery.getName(), String.valueOf(account), pasd, salt, email, LocalDateTime.now());

        boolean b1 = userMapper.insertUser(addUserDto);
        if(!b1){
            return JsonResultVo.fail("注册失败，联系管理员");
        }

        String token = JwtUtil.sign(String.valueOf(addUserDto.getId()), RoleEnum.USER);

        UserRegisterVo userRegisterVo = new UserRegisterVo(String.valueOf(account), email, token);

        return JsonResultVo.success("注册成功",userRegisterVo);

    }

    /**
     * 用户登陆
     * @param userLoginQuery 登陆参数
     * @return token等
     */
    @Override
    public JsonResultVo<UserRegisterVo> login(UserLoginQuery userLoginQuery) {
        if(userLoginQuery==null){
            return JsonResultVo.fail("参数为空");
        }
        String account = userLoginQuery.getAccount();
        String password = userLoginQuery.getPassword();
        QueryUserDto user = userMapper.getUser(account);
        if(user==null){
            return JsonResultVo.fail("不存在此账号");
        }
        if(!user.getPassword().equals(CodeUtil.md5(password+user.getSalt()))){
            return JsonResultVo.fail("密码错误");
        }
        String token = JwtUtil.sign(String.valueOf(user.getId()), RoleEnum.USER);
        UserRegisterVo userRegisterVo = new UserRegisterVo(account, user.getEmail(), token);
        return JsonResultVo.success("登陆成功",userRegisterVo);
    }


}



























